package com.mashuai.dnsip;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @ClassName HttpClient
 * @Description http访问工具
 * @Author MaShuai
 * @Date 2018/11/26 10:43
 * @Version 1.0
 **/
public class HttpClient {

    private static int TIMEOUT = 60000;
    private static String SCHEME = "https";
    private static String HOST = "172.17.1.1";
    private static int PORT = 3128;
    private static String USERNAME = "mashuai@lingtu.com";
    private static String PASSWORD = "lingtu654321";


    /**
     * @Description 配置代理联网
     * @Param [httpProxy]
     * @return org.apache.http.HttpHost
     */
    public static HttpHost getHost(){
        HttpHost proxy = new HttpHost(HOST,PORT,SCHEME);
        return proxy;
    }

    /**
     * @Description 配置代理账号密码认证对象
     * @Param [httpProxy]
     * @return org.apache.http.client.CredentialsProvider
     */
    public static CredentialsProvider setCredentials(){
        UsernamePasswordCredentials upc = new UsernamePasswordCredentials(USERNAME, PASSWORD);
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(getHost()), upc);
        return provider;
    }

    /**
     * @Description get,代理获取
     * @Param [url, httpProxy]
     * @return java.lang.String
     */
    public static String doGet(String url) {

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            RequestConfig requestConfig = RequestConfig.custom()
                    //.setProxy(getHost())
                    // 连接主机服务超时时间
                    .setConnectTimeout(TIMEOUT)
                    // 请求超时时间
                    .setConnectionRequestTimeout(TIMEOUT)
                    // 数据读取超时时间
                    .setSocketTimeout(TIMEOUT)
                    .build();
            // 通过默认代理配置创建一个httpClient实例
            //httpClient = HttpClients.custom().setDefaultCredentialsProvider(setCredentials()).build();
            httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            // 设置配置请求参数

            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity, "gb2312");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * @Description post
     * @Param [url, paramMap]
     * @return java.lang.String
     */
    public static String doPost(String url, Map<String, Object> paramMap) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        // 创建httpClient实例
        httpClient = HttpClients.custom().setDefaultCredentialsProvider(setCredentials()).build();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 配置请求参数实例
        RequestConfig requestConfig = RequestConfig.custom()
                .setProxy(getHost())
                // 设置连接主机服务超时时间
                .setConnectTimeout(TIMEOUT)
                // 设置连接请求超时时间
                .setConnectionRequestTimeout(TIMEOUT)
                // 设置读取数据连接超时时间
                .setSocketTimeout(TIMEOUT)
                .build();
        // 为httpPost实例设置配置
        httpPost.setConfig(requestConfig);
        // 设置请求头
        //httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循环遍历，获取迭代器
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> mapEntry = iterator.next();
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }

            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static void main(String[] args){
        //String html = doGet("http://2019.ip138.com/ic.asp");
        //System.out.println(html);
        Document doc = Jsoup.parse("<html>\n" +
                "<head>\n" +
                "<meta http-equiv=\"content-type\" content=\"text/html; charset=gb2312\">\n" +
                "<title> 您的IP地址 </title>\n" +
                "</head>\n" +
                "<body style=\"margin:0px\"><center>您的IP是：[123.66.146.19] 来自：北京市北京市 铁通</center></body></html>");
        Elements elements = doc.getElementsByTag("center");
        String ip = "";
        for(Element element : elements){
            ip = element.text();
        }
        System.out.println("我的ip：" + ip);


        String myIp = ip.replaceAll(" ", "").split("\\[")[1].split("\\]")[0];
        System.out.println(myIp);
    }

}

